package com.quyeying.config.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName 线程配置类
 * @Description TODO
 * @Author Jll
 * @Date 2022/6/17 10:12
 * @Version 1.0
 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig {


    @Value("${asyncConfig.corePoolSize}")
    private int corePoolSize;

    @Value("${asyncConfig.maxPoolSize}")
    private int maxPoolSize;

    @Value("${asyncConfig.queueCapacity}")
    private int queueCapacity;

    @Value("${asyncConfig.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Value("${asyncConfig.threadNamePrefix}")
    private String threadNamePrefix;


    @Bean("asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //等待队列的大小
        executor.setQueueCapacity(queueCapacity);
        //空闲线程的存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }

}
